package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.WxSendResponse;
import com.ruoyi.system.mapper.WxSendResponseMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class EnterpriseWXServiceImpl {
    @Value("${enterprise.wx.url}")
    private String url;

    @Value("${enterprise.wx.corpId}")
    private String corpId;

    @Value("${enterprise.wx.corpSecret}")
    private String corpSecret;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WxSendResponseMapper wxSendResponseMapper;

    private static final String ACCESS_TOKEN_URL = "/gettoken?corpid=%s&corpsecret=%s";

    private static final String SEND_MESSAGE = "/message/send?access_token=%s";

    @Data
    public static class AccessTokenResponse {

        private Integer errcode;
        private String errmsg;

        private String access_token;

        private String expires_in;

    }

    private String getAccessToken() {
        String requestUrl = url + String.format(ACCESS_TOKEN_URL, corpId, corpSecret);
        String sendGet = HttpUtils.sendGet(requestUrl);
        if (StringUtils.isNotEmpty(sendGet)) {
            AccessTokenResponse accessTokenResponse = JSON.parseObject(sendGet, AccessTokenResponse.class);
            if (!accessTokenResponse.getErrcode().equals(0)) {
                log.error("EnterpriseWXServiceImpl.getAccessToken 异常:{}", accessTokenResponse.errmsg);
                return "";
            }

            redisCache.setCacheObject("enterprise.wx.access.token", accessTokenResponse.getAccess_token(),
                    Integer.valueOf(accessTokenResponse.getExpires_in()), TimeUnit.SECONDS);

            return accessTokenResponse.getAccess_token();
        }
        return "";
    }

    @Data
    public static class SendMessageRequest {

        private String touser;

        private String toparty;

        private String totag;

        private String msgtype;

        private Integer agentid;

        private MessageContent text;

        private Integer safe;

        private Integer enable_id_trans;

        private Integer enable_duplicate_check;

        private Integer duplicate_check_interval;

    }

    @Data
    public static class MessageContent {

        private String content;

    }

    @Data
    public static class SendMessageResponse {

        private Integer errcode;
        private String errmsg;

        private String invaliduser;

        private String invalidparty;

        private String invalidtag;

        private String unlicenseduser;

        private String msgid;

        private String response_code;

    }

    public void sendMessageToWx(String message, String userWxId) {
        SendMessageRequest sendMessageRequest = new SendMessageRequest();
        sendMessageRequest.setTouser(userWxId);
        sendMessageRequest.setMsgtype("text");
        sendMessageRequest.setAgentid(1000319);
        MessageContent messageContent = new MessageContent();
        messageContent.setContent(message);
        sendMessageRequest.setText(messageContent);
        pushMessage(sendMessageRequest);
    }


    public void pushMessage(SendMessageRequest sendMessageRequest) {
      /*  if (StringUtils.isEmpty(sendMessageRequest.getTouser())) {
            return;
        }*/

        WxSendResponse wxSendResponse = null;

        String accessToken = "";
        Boolean aBoolean = redisCache.hasKey("enterprise.wx.access.token");
        if (aBoolean) {
            accessToken = redisCache.getCacheObject("enterprise.wx.access.token");
        } else {
            accessToken = getAccessToken();
        }
        String requestUrl = url + String.format(SEND_MESSAGE, accessToken);
        log.info("==========发送消息=========  入参" + JSON.toJSONString(sendMessageRequest));
        String sendPost = HttpUtils.sendPost(requestUrl, JSON.toJSONString(sendMessageRequest));
        log.info("==========发送消息=========  出参" + sendPost);
        if (StringUtils.isNotEmpty(sendPost)) {
            SendMessageResponse sendMessageResponse = JSON.parseObject(sendPost, SendMessageResponse.class);
            if (!sendMessageResponse.getErrcode().equals(0)) {
                wxSendResponse = WxSendResponse.builder().sendUrl(requestUrl)
                        .sendParam(JSON.toJSONString(sendMessageRequest)).sendResponse(sendPost).sendStatus("失败").createdBy("sys").createdDate(new Date())
                        .build();
                log.error("EnterpriseWXServiceImpl.pushMessage 异常:{}", sendMessageResponse.errmsg);
            } else {
                wxSendResponse = WxSendResponse.builder().sendUrl(requestUrl)
                        .sendParam(JSON.toJSONString(sendMessageRequest)).sendResponse(sendPost).sendStatus("成功").createdBy("sys").createdDate(new Date())
                        .build();
            }
        }

        wxSendResponseMapper.insert(wxSendResponse);
    }

}
